using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Data;
using System.Reflection;

namespace Sys.DataAccess
{
    public static class DataConverter
    {
        public static CollectionT GetCollectionFromTable<T, CollectionT>(DataTable table)
            where CollectionT : Collection<T>, new()
        {
            CollectionT collection = new CollectionT();
            T t;
            foreach (DataRow row in table.Rows)
            {
                if (row[0] != null && row[0] != DBNull.Value)
                {
                    t = (T)row[0];
                    collection.Add(t);
                }
            }
            return collection;
        }

        public static List<T> GetListFromTable<T>(DataTable table)
        {
            return new List<T>(GetCollectionFromTable<T, Collection<T>>(table));
        }

        public static void MapExcept(object source, object dest, List<string> exceptProperties)
        {
            Type srcType = source.GetType();
            Type destType = dest.GetType();
            PropertyInfo destProp;
            foreach (PropertyInfo propInfo in srcType.GetProperties())
            {
                //if its in the except list, then dont map
                if (exceptProperties.Contains(propInfo.Name)) continue;
                destProp = destType.GetProperty(propInfo.Name);
                destProp.SetValue(dest, propInfo.GetValue(source, null), null);
            }
        }

        public static void MapExcept(object source, object dest, string commaSeperatedExceptProperties)
        {
            List<string> exceptProperties = new List<string>(commaSeperatedExceptProperties.Split(','));
            MapExcept(source, dest, exceptProperties);
        }
    }
}
